<template>
    <div class="manage-book-page">
        <el-card>
            <h2 style="text-align: center; margin-bottom: 24px">
                册子信息管理
            </h2>
            <div
                style="
                    display: flex;
                    gap: 16px;
                    align-items: center;
                    margin-bottom: 16px;
                "
            >
                <el-input
                    v-model="searchName"
                    placeholder="搜索角色名称"
                    clearable
                    style="width: 200px"
                />
            </div>
            <el-table :data="pagedBooks" class="book-table">
                <el-table-column prop="name" label="名称" width="120" />
                <el-table-column prop="avatar" label="头像" width="100">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.avatar"
                            :src="scope.row.avatar"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.avatar]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookfront1"
                    label="书本封面正面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookfront1"
                            :src="scope.row.bookfront1"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookfront1]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookfront2"
                    label="书本封面背面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookfront2"
                            :src="scope.row.bookfront2"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookfront2]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookPage1"
                    label="内容页正面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookPage1"
                            :src="scope.row.bookPage1"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookPage1]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookPage2"
                    label="内容页背面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookPage2"
                            :src="scope.row.bookPage2"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookPage2]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="bookBack" label="书本封底" width="100">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookBack"
                            :src="scope.row.bookBack"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookBack]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="Layers"
                    label="图层(Layers)"
                    width="80"
                />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="primary"
                            @click="openEdit(scope.row)"
                            >编辑</el-button
                        >
                        <el-popconfirm
                            title="确定删除该册子吗？"
                            @confirm="handleDelete(scope.row)"
                            confirm-button-text="删除"
                            cancel-button-text="取消"
                        >
                            <template #reference>
                                <el-button size="small" type="danger"
                                    >删除</el-button
                                >
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; margin: 24px 0">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :page-size="pageSize"
                    :total="books.length"
                    v-model:current-page="currentPage"
                />
            </div>
        </el-card>
        <!-- 编辑对话框 -->
        <el-dialog
            v-model="showEditDialog"
            title="编辑册子信息"
            width="1100px"
            center
        >
            <el-form :model="editForm" label-width="140px">
                <el-row :gutter="40">
                    <el-col :span="12">
                        <el-form-item label="名称">
                            <el-input v-model="editForm.name" />
                        </el-form-item>
                        <el-form-item label="简介">
                            <el-input
                                v-model="editForm.desc"
                                type="textarea"
                                rows="4"
                            />
                        </el-form-item>
                        <el-form-item label="是否显示头像">
                            <el-switch v-model="editForm.isAvatar" />
                        </el-form-item>
                        <el-form-item label="头像链接">
                            <el-input v-model="editForm.avatar" />
                            <el-image
                                v-if="editForm.avatar"
                                :src="editForm.avatar"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.avatar]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封面正面">
                            <el-input v-model="editForm.bookfront1" />
                            <el-image
                                v-if="editForm.bookfront1"
                                :src="editForm.bookfront1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookfront1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封面背面">
                            <el-input v-model="editForm.bookfront2" />
                            <el-image
                                v-if="editForm.bookfront2"
                                :src="editForm.bookfront2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookfront2]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="内容页正面">
                            <el-input v-model="editForm.bookPage1" />
                            <el-image
                                v-if="editForm.bookPage1"
                                :src="editForm.bookPage1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookPage1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="内容页背面">
                            <el-input v-model="editForm.bookPage2" />
                            <el-image
                                v-if="editForm.bookPage2"
                                :src="editForm.bookPage2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookPage2]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封底">
                            <el-input v-model="editForm.bookBack" />
                            <el-image
                                v-if="editForm.bookBack"
                                :src="editForm.bookBack"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookBack]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item>
                            <h1>页组使用教程</h1>
                            <el-image
                                src="https://s3plus.meituan.net/opapisdk/op_ticket_1_885190757_1761851162301_qdqqd_1f1q81.png"
                                style="width: 20rem; margin-top: 8px"
                                fit="contain"
                                :preview-src-list="[
                                    `https://s3plus.meituan.net/opapisdk/op_ticket_1_885190757_1761851162301_qdqqd_1f1q81.png`,
                                    `https://zkaicc.huilan.com/aicc/api/aicc-file/miniofile/preViewPicture/aicc/qdqqd_1761851209348.png`,
                                    `https://s3plus.meituan.net/opapisdk/op_ticket_1_885190757_1761851215826_qdqqd_v8woih.png`,
                                ]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="旋转Y">
                            <el-input-number
                                v-model="editForm.rotateY"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                        <el-form-item label="旋转X">
                            <el-input-number
                                v-model="editForm.rotateX"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                        <el-form-item label="打开方向">
                            <el-select
                                v-model="editForm.transformOrigin"
                                placeholder="请选择打开方向"
                            >
                                <el-option
                                    label="向左打开"
                                    value="left center"
                                />
                                <el-option
                                    label="向右打开"
                                    value="right center"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="文字颜色">
                            <el-color-picker v-model="editForm.color" />
                        </el-form-item>
                        <el-form-item label="头像Top">
                            <el-input-number
                                v-model="editForm.avatarTop"
                                :min="0"
                                :max="100"
                            />
                        </el-form-item>
                        <el-form-item label="头像Left">
                            <el-input-number
                                v-model="editForm.avatarLeft"
                                :min="0"
                                :max="100"
                            />
                        </el-form-item>
                        <el-form-item label="图层(Layers)">
                            <el-input-number
                                v-model="editForm.Layers"
                                :min="0"
                                :max="9999"
                                :step="1"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="书本离顶部的距离">
                            <el-input-number
                                v-model="editForm.bookTop"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                        <el-form-item label="书本离左侧的距离">
                            <el-input-number
                                v-model="editForm.bookLeft"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- essay 编辑等 -->
                <el-form-item label="书本内容" class="essay-form-item">
                    <div
                        v-for="(page, pageIdx) in editForm.essay"
                        :key="pageIdx"
                        class="essay-page-block"
                    >
                        <el-divider>第{{ pageIdx + 1 }}组页</el-divider>
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <el-form-item label="页码">
                                    <el-input
                                        v-model="page.PagesNumeStr"
                                        style="width: 400px"
                                        placeholder="如 1,2"
                                        @change="
                                            (val) =>
                                                handleEditPagesNumeChange(
                                                    page,
                                                    val
                                                )
                                        "
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="24">
                            <!-- 正面内容 -->
                            <el-col :span="12">
                                <div class="essay-content-title">正面内容</div>
                                <div
                                    v-for="(item, idx) in page.frontContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <el-select
                                        v-model="item.type"
                                        placeholder="类型"
                                        style="width: 180px"
                                        @change="
                                            (val) =>
                                                handleEssayTypeChange(
                                                    val,
                                                    item,
                                                    page.frontContent
                                                )
                                        "
                                    >
                                        <el-option label="文本" value="text" />
                                        <el-option label="图片" value="img" />
                                        <el-option label="图片2" value="img2" />
                                        <el-option label="图片3" value="img3" />
                                    </el-select>
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            v-model="item.text"
                                            type="textarea"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                    <el-button
                                        icon="el-icon-delete"
                                        type="danger"
                                        size="small"
                                        @click="
                                            removeEditEssayContent(
                                                page.frontContent,
                                                idx
                                            )
                                        "
                                        circle
                                    />
                                </div>
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="
                                        addEditEssayContent(page.frontContent)
                                    "
                                    :disabled="
                                        isEditEssayContentDisabled(
                                            page.frontContent
                                        )
                                    "
                                    style="margin-top: 8px"
                                    >添加内容</el-button
                                >
                            </el-col>
                            <!-- 背面内容 -->
                            <el-col :span="12">
                                <div class="essay-content-title">背面内容</div>
                                <div
                                    v-for="(item, idx) in page.backContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <el-select
                                        v-model="item.type"
                                        placeholder="类型"
                                        style="width: 180px"
                                        @change="
                                            (val) =>
                                                handleEssayTypeChange(
                                                    val,
                                                    item,
                                                    page.backContent
                                                )
                                        "
                                    >
                                        <el-option label="文本" value="text" />
                                        <el-option label="图片" value="img" />
                                        <el-option label="图片2" value="img2" />
                                        <el-option label="图片3" value="img3" />
                                    </el-select>
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            v-model="item.text"
                                            type="textarea"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                    <el-button
                                        icon="el-icon-delete"
                                        type="danger"
                                        size="small"
                                        @click="
                                            removeEditEssayContent(
                                                page.backContent,
                                                idx
                                            )
                                        "
                                        circle
                                    />
                                </div>
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="
                                        addEditEssayContent(page.backContent)
                                    "
                                    :disabled="
                                        isEditEssayContentDisabled(
                                            page.backContent
                                        )
                                    "
                                    style="margin-top: 8px"
                                    >添加内容</el-button
                                >
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-button
                                    size="small"
                                    type="danger"
                                    @click="removeEditEssayPage(pageIdx)"
                                    style="margin-top: 12px"
                                    >删除本组页</el-button
                                >
                            </el-col>
                        </el-row>
                    </div>
                    <el-button
                        size="large"
                        type="success"
                        @click="addEditEssayPage"
                        style="margin-top: 18px"
                        >添加页组</el-button
                    >
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleEditSave"
                    :loading="editLoading"
                    >保存</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getAllBookData, updateBookData, deleteBookData } from "./api";

const books = ref([]);
const searchName = ref("");
const currentPage = ref(1);
const pageSize = 5;

const filteredBooks = computed(() => {
    return books.value.filter((item) => {
        return searchName.value
            ? (item.name || "").includes(searchName.value)
            : true;
    });
});
const pagedBooks = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return filteredBooks.value.slice(start, start + pageSize);
});
const showEditDialog = ref(false);
const editLoading = ref(false);
const editForm = reactive({
    _id: "",
    userId: "",
    name: "",
    desc: "",
    avatar: "",
    isAvatar: false,
    essay: [],
    bookfront1: "",
    bookfront2: "",
    bookPage1: "",
    bookPage2: "",
    bookBack: "",
    rotateY: 13,
    rotateX: 7,
    bookTop: 0,
    bookLeft: 0,
    transformOrigin: "",
    color: "#000000ff",
    avatarTop: 5,
    avatarLeft: 50,
    Layers: 999,
});

const operatorId = sessionStorage.getItem("user_id");

function fetchBooks() {
    getAllBookData().then((res) => {
        books.value = res;
        currentPage.value = 1;
    });
}

function openEdit(row) {
    Object.keys(editForm).forEach((k) => delete editForm[k]);
    Object.assign(editForm, row);
    if (editForm.essay && Array.isArray(editForm.essay)) {
        editForm.essay.forEach((page) => {
            page.PagesNumeStr = (page.PagesNume || []).join(",");
        });
    }
    showEditDialog.value = true;
}

function handleEditSave() {
    if (!editForm.name) {
        ElMessage.warning("名称不能为空");
        return;
    }
    editLoading.value = true;
    updateBookData(editForm._id, {
        operatorId,
        ...editForm,
    })
        .then((res) => {
            ElMessage.success(res.message);
            showEditDialog.value = false;
            fetchBooks();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "更新失败");
        })
        .finally(() => {
            editLoading.value = false;
        });
}

function handleDelete(row) {
    deleteBookData(row._id, operatorId)
        .then((res) => {
            ElMessage.success(res.message);
            fetchBooks();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "删除失败");
        });
}

function addEditEssayPage() {
    let maxPage = 0;
    (editForm.essay || []).forEach((page) => {
        if (Array.isArray(page.PagesNume) && page.PagesNume.length > 0) {
            const localMax = Math.max(...page.PagesNume);
            if (localMax > maxPage) maxPage = localMax;
        }
    });
    const newPages = [maxPage + 1, maxPage + 2];
    editForm.essay.push({
        PagesNume: newPages,
        PagesNumeStr: newPages.join(","),
        frontContent: [],
        backContent: [],
    });
}
function removeEditEssayPage(idx) {
    editForm.essay.splice(idx, 1);
}
function addEditEssayContent(arr) {
    arr.push({ type: "text", text: "" });
}
function removeEditEssayContent(arr, idx) {
    arr.splice(idx, 1);
}
function handleEditPagesNumeChange(page, val) {
    page.PagesNume = val
        .split(",")
        .map((v) => parseInt(v.trim()))
        .filter((v) => !isNaN(v));
    page.PagesNumeStr = val;
}
function isEditEssayContentDisabled(arr) {
    if (!arr || arr.length === 0) return false;
    if (["img2", "img3"].includes(arr[0].type)) return true;
    return arr.length >= 3;
}
function handleEssayTypeChange(val, item, arr) {
    if (val === "img2" || val === "img3") {
        arr.splice(0, arr.length, item);
        item.type = val;
        delete item.text;
    } else {
        if (arr.length === 1 && ["img2", "img3"].includes(arr[0].type)) {
            arr.splice(0, 1, item);
        }
        item.type = val;
    }
}

onMounted(fetchBooks);
</script>

<style scoped>
.manage-book-page {
    padding: 32px 0;
    display: flex;
    justify-content: center;
}
.book-table {
    margin-top: 32px;
}
</style>